import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  BadRequestException,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class UserFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    //如果是错误请求对象
    if (exception instanceof BadRequestException) {
      //获取错误请求对象
      const errorObj = exception.getResponse() as any;
      //自定义错误
      response.status(status).json({
        statusCode: status,
        data: errorObj.message.map((item) => {
          return {
            key: item.property,
            message: item.constraints.isNotEmpty,
          };
        }),
      });
    }
  }
}
